<template>
  <TslChart
    ref="chartRef"
    width="100%"
    height="100%"
    :play="false"
    :config="chartConfig"
    class="trend-chart"
  />
</template>

<script setup lang="ts">
import { TslChart, defineBaseLine, defaultHorizontalLegend } from '@tslsmart/charts'
import type { HoldItem } from '@/indexDB/initHold'
import type { HoldHistoryItem } from '@/indexDB/initHistory'
import { computed, ref, watchEffect } from 'vue'
import dayjs from 'dayjs'
import TimeTrend from './timeTrend?worker'

const props = defineProps<{
  historyList: HoldHistoryItem[]
  holdList: HoldItem[]
  total: number
}>()

const chartRef = ref()

const timeTrendWorker = new TimeTrend()
const timeHoldList = ref([])

timeTrendWorker.addEventListener('message', (e) => {
  timeHoldList.value = e.data
  chartRef.value?.refresh()
})

const chartConfig = computed(() => {
  let timeList: string[] = []
  let timeValueList: number[] = []
  let timeEarningsList: number[] = []
  let timeEarningsPercentList: number[] = []
  timeHoldList.value.forEach((timeHold) => {
    const { time, timeValue, timeEarnings, timeEarningsPercent } = timeHold
    timeList.push(dayjs(time).format('MM-DD'))
    timeValueList.push(timeValue)
    timeEarningsList.push(timeEarnings)
    timeEarningsPercentList.push(timeEarningsPercent)
  })
  return defineBaseLine({
    data: [
      {
        name: '总市值',
        data: timeValueList
      },
      {
        name: '持有收益',
        data: timeEarningsList
      },
      {
        name: '持有收益率',
        data: timeEarningsPercentList
      }
    ],
    xAxisData: timeList,

    grid: {
      top: 60,
      right: 20,
      left: 60,
      bottom: 40
    },
    legend: {
      ...defaultHorizontalLegend(),
      left: undefined,
      right: 20,
      top: 16
    }
  })
})

watchEffect(() => {
  console.log('refresh', props.total)

  timeTrendWorker.postMessage(
    JSON.stringify({ historyList: props.historyList, holdList: props.holdList })
  )
})
</script>
